//
//  HomeViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/15.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "HomeViewController.h"
#import "SearchViewController.h"
#import "NavigationController.h"
#import "SearchView.h"
#import "TabBarController.h"
#import "UIView+TransitionAnimation.h"

#import "SearchTraceViewController.h"
#import "TracingViewController.h"
#import "UserInfoViewController.h"
#import "RoutePlanViewController.h"
#import "AlarmViewController.h"
#import "LocationAnnotationView.h"
#import "EquipmentModel.h"
#import "TraceModel.h"

#import "ErrorInfoUtility.h"
#import "Utility.h"

#import "CoordinateQuadTree.h"
#import "ClusterAnnotationView.h"
#import "LocationManager.h"

#define kSize 1000
#define kReuseIndetifier @"annotationReuseIndetifier"
#define kSendBtnTitleNotification @"kSendBtnTitleNotification"
#define kIsNeedLayoutNotification @"kIsNeedLayoutNotification"

@interface HomeViewController ()<UITextFieldDelegate,SearchTableViewCellDelegate>

@property (nonatomic, strong) SearchView *searchView;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, assign) FuncKeyType funcKeyType;

@property (nonatomic, strong) TraceModel *traceModel;

@property (nonatomic, copy  ) NSString *formattedAddress;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) NSMutableArray *annotations;
////////////////////点聚合////////////////////
@property (nonatomic, strong) CoordinateQuadTree *coordinateQuadTree;
@property (nonatomic, strong) CustomCalloutView *customCalloutView;
@property (nonatomic, strong) ClusterAnnotationView *annotationView;
@property (nonatomic, strong) NSMutableArray *selectedPoiArray;
@property (nonatomic, assign) BOOL shouldRegionChangeReCalculate;
@property (nonatomic, strong) EquipmentModel *annotation;

@property (nonatomic, copy) NSString *tempDeptId;
@property (nonatomic, copy) NSString *childDeptId;

//@property (nonatomic) BOOL _isDarkMode;

@end

@implementation HomeViewController

- (id)init {
    if (self = [super init]) {
        self.coordinateQuadTree = [[CoordinateQuadTree alloc] init];
        self.selectedPoiArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavgationBar];

    self.page = 1;
    
    _shouldRegionChangeReCalculate = NO;
    
    // 加载设备列表
    //[self loadEquipsData];
    
    [self configSubviews];
    
    self.mapView.zoomLevel = 3;

    [[NSNotificationCenter defaultCenter]
     addObserver:self
        selector:@selector(pushToNextController:)
            name:kSendBtnTitleNotification
          object:nil];
    
    // 是否支持camera旋转
    self.mapView.rotateCameraEnabled = NO;
    self.mapView.rotateEnabled = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar  setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    // 导航栏透明
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    self.childDeptId = [User sharedUser].deptModel.childDeptId;
    
    if (![self.tempDeptId isEqualToString:self.childDeptId]) {
        self.page = 1;
        [self.dataSource removeAllObjects];
        [MBProgressHUD showHUDAddedTo:kWindow animated:YES];
        [self loadEquipsData];
    }
}

- (void)addAnnotationsToMapView
{
    self.shouldRegionChangeReCalculate = NO;
    
    NSMutableArray *annosToRemove = [NSMutableArray arrayWithArray:self.mapView.annotations];
    [annosToRemove removeObject:self.mapView.userLocation];
    [self.mapView removeAnnotations:annosToRemove];
    
    if (!self.dataSource.count) {return;}

    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        /* 建立四叉树. */
        [weakSelf.coordinateQuadTree buildTreeWithPOIs:self.dataSource];
        weakSelf.shouldRegionChangeReCalculate = YES;
        [weakSelf addAnnotationsToMapView:weakSelf.mapView];
    });
}

- (void)loadEquipsData {
    //NSString *deptId = [User sharedUser].deptModel.childDeptId;
    [self.requestTool loadEquipsByPage:self.page size:kSize status:@"" actStatus:@"" str:@"" deptId:self.childDeptId show:NO success:^(NSArray *equips, NSArray *equipCounts) {
        for (EquipmentModel *eModel in equips) {
            if (eModel.pointModel.lat && eModel.pointModel.lng)
            {// 禁用的设备
                if (![eModel.mark isEqualToString:@"D"]) {
                    [self.dataSource addObject:eModel];
                }
            }
        }
        // 不足1000条，说明是最后一页
        if (equips.count >= kSize) {
            self.page ++;
            [self loadEquipsData];
        } else {
            PPLog(@"设备个数的啦 == %ld",self.dataSource.count);
            [MBProgressHUD hideHUDForView:KEY_WINDOW];
            self.tempDeptId = [User sharedUser].deptModel.childDeptId;
            [self addAnnotationsToMapView];
        }
    } failure:^(NSString *error) {
        PPLog(@"load equips error = %@",error);
    }];
}

//- (void)loadEquipListData
//{
//    [self.requestTool loadEquipmentListByPage:self.page size:kSize status:@"" actStatus:@"" str:@"" isNeedDeptId:YES show:NO success:^(NSArray *equipments,NSArray *equipCounts) {
//        for (EquipmentModel *eModel in equipments) {
//            if (eModel.pointModel.lat && eModel.pointModel.lng)
//            {// 禁用的设备
//                if (![eModel.mark isEqualToString:@"D"]) {
//                    [self.dataSource addObject:eModel];
//                }
//            }
//        }
//        // 分页请求，直到不足1000条，说明是最后一页
//        if (equipments.count >= kSize) {
//            self.page ++;
//            [self loadEquipListData];
//        } else {
//            [MBProgressHUD hideHUDForView:KEY_WINDOW];
//            if (self.dataSource.count) {
//                [self addAnnotationsToMapView];
//            }
//        }
//    } failure:^(NSError *error) {
//        PPLog(@"load eq list error = %@",error);
//    }];
//}

- (void)configSubviews
{
    [self initMapView];
    [self setupButton];
}

/* 更新annotation. */
- (void)updateMapViewAnnotationsWithAnnotations:(NSArray *)annotations
{
    /* 用户滑动时，保留仍然可用的标注，去除屏幕外标注，添加新增区域的标注 */
    NSMutableSet *before = [NSMutableSet setWithArray:self.mapView.annotations];
    [before removeObject:[self.mapView userLocation]];
    NSSet *after = [NSSet setWithArray:annotations];
    
    /* 保留仍然位于屏幕内的annotation. */
    NSMutableSet *toKeep = [NSMutableSet setWithSet:before];
    [toKeep intersectSet:after];//取交集
    
    /* 需要添加的annotation. */
    NSMutableSet *toAdd = [NSMutableSet setWithSet:after];
    [toAdd minusSet:toKeep];//删除toAdd中与toKeep相同的元素
    
    /* 删除位于屏幕外的annotation. */
    NSMutableSet *toRemove = [NSMutableSet setWithSet:before];
    [toRemove minusSet:after];
    
    /* 更新. */
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mapView addAnnotations:[toAdd allObjects]];
        [self.mapView removeAnnotations:[toRemove allObjects]];
    });
}

- (void)addAnnotationsToMapView:(MAMapView *)mapView
{
    @synchronized(self)
    {
        if (self.coordinateQuadTree.root == nil || !self.shouldRegionChangeReCalculate)
        {
            PPLog(@"tree is not ready.");
            return;
        }
        
        /* 根据当前zoomLevel和zoomScale 进行annotation聚合. */
        MAMapRect visibleRect = self.mapView.visibleMapRect;
        double zoomScale = self.mapView.bounds.size.width / visibleRect.size.width;
        double zoomLevel = self.mapView.zoomLevel;
//        PPLog(@"current thread = %@",[NSThread currentThread]);
        
        /* 也可根据zoomLevel计算指定屏幕距离(以50像素为例)对应的实际距离 进行annotation聚合. */
        /* 使用：NSArray *annotations = [weakSelf.coordinateQuadTree clusteredAnnotationsWithinMapRect:visibleRect withDistance:distance]; */
        //double distance = 50.f * [self.mapView metersPerPointForZoomLevel:self.mapView.zoomLevel];
        
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSArray *annotations = [weakSelf.coordinateQuadTree clusteredAnnotationsWithinMapRect:visibleRect
                                                                                    withZoomScale:zoomScale
                                                                                     andZoomLevel:zoomLevel];
            /* 更新annotation. */
            [weakSelf updateMapViewAnnotationsWithAnnotations:annotations];
        });
    }
}


#pragma mark - MAMapViewDelegate -

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    
    if ([annotation isKindOfClass:[EquipmentModel class]])
    {
        ClusterAnnotationView *annotationView = (ClusterAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:kReuseIndetifier];
        
        if (annotationView == nil) {
            annotationView = [[ClusterAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:kReuseIndetifier];
            annotationView.canShowCallout = NO;
        }
        
        /* 设置annotationView的属性. */
        //annotationView.annotation = annotation;
        annotationView.count = [(EquipmentModel *)annotation count];
        annotationView.dataSource = self.dataSource;
        
        return annotationView;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    if ([view.annotation isKindOfClass:[EquipmentModel class]]) {
        EquipmentModel *annotation = (EquipmentModel *)view.annotation;
        self.annotation = annotation;
        
        if (annotation.pois.count >= 2) {//以中心点为圆心放大
            [self changeCenterTo:view.annotation.coordinate];
        } else {
            self.annotationView = (ClusterAnnotationView *)view;
            
            CGFloat scale = 0.00;
            if (kScreenHeight == 568) { // 5
                scale = 0.78;
            } else if (kScreenHeight == 667) { // 6
                scale = 0.66;
            } else if (kScreenHeight == 736) { // 6p
                scale = 0.63;
            }
            //地图的视图锚点(坐标系归一化)，默认为(0.5, 0.5)，即当前地图的视图中心.
            MAMapStatus *status = [self.mapView getMapStatus];
            [status setScreenAnchor:CGPointMake(0.5,scale)];
            [self.mapView setMapStatus:status animated:NO];
            [self.mapView setCenterCoordinate:annotation.coordinate animated:NO];
            //根据设备号加载最新的设备信息
            [self loadEquipLatestInfo:((EquipmentModel *)annotation.pois[0]).eqNo];
        }
    }
    
    if ([view.annotation isKindOfClass:[MAUserLocation class]]){
        MAMapStatus *status = [self.mapView getMapStatus];
        status.screenAnchor = CGPointMake(0.5,0.5);
        [self.mapView setMapStatus:status animated:YES];
        [mapView setCenterCoordinate:view.annotation.coordinate animated:YES];
    }
}

- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate {
    //    [self changeCenterTo:coordinate];
}

- (void)changeCenterTo:(CLLocationCoordinate2D)newLoc
{
    [self.mapView setCenterCoordinate:newLoc animated:NO];
    int zoomLevel = self.mapView.zoomLevel;
    [self.mapView setZoomLevel:(zoomLevel+1)];
}

- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    [self addAnnotationsToMapView:self.mapView];
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    /* 自定义定位精度对应的MACircleView */
    if (overlay == mapView.userLocationAccuracyCircle)
    {
        MACircleRenderer *accuracyCircleRenderer = [[MACircleRenderer alloc] initWithCircle:(MACircle *)overlay];
        
        accuracyCircleRenderer.strokeColor  = kMAOverlayRendererDefaultStrokeColor;
        accuracyCircleRenderer.fillColor    = [kBaseColor colorWithAlphaComponent:0.1];
        
        return accuracyCircleRenderer;
    }
    return nil;
}

- (void)pushToNextController:(NSNotification *)noti
{
    NSInteger btnTag = [noti.userInfo[@"tag"] integerValue];
    EquipmentModel *model = [noti object];
    
    switch (btnTag)
    {
        /**轨迹回放*/
        case FuncKeyTypeReplayTrace:
        {
            SearchTraceViewController *chooseTime = [[SearchTraceViewController alloc] init];
            chooseTime.eqNo = model.eqNo;
            chooseTime.ownerName = model.ownerName;
            [self.navigationController pushViewController:chooseTime animated:YES];
        }
            break;
        /**重新定位*/
        case FuncKeyTypeRelocation:
        {
            [self loadEquipLatestInfo:model.eqNo];
        }
            break;
        /**实时跟踪*/
        case FuncKeyTypeTracing:
        {
            TracingViewController *tracing = [[TracingViewController alloc] init];
            tracing.eqNo = model.eqNo;
            tracing.ownerName = model.ownerName;
            tracing.cnStatus = model.cnStatus;
            tracing.isNeedDeptId = YES;
            [self.navigationController pushViewController:tracing animated:YES];
        }
            break;
        /**用户信息*/
        case FuncKeyTypeUserInfo:
        {
            UserInfoViewController *userInfo = [[UserInfoViewController alloc] init];
            userInfo.eqNo = model.eqNo;
            userInfo.isNeedDeptId = YES;
            [self.navigationController pushViewController:userInfo animated:YES];
        }
            break;
        /**设备报警*/
        case FuncKeyTypeDeviceAlarm:
        {
            AlarmViewController *alarm = [[AlarmViewController alloc] init];
            alarm.eqNo = model.eqNo;
            alarm.egId = model.egId;
            [self.navigationController pushViewController:alarm animated:YES];
        }
            break;
        /**一键导航*/
        case FuncKeyTypeNavigator:
        {
            RoutePlanViewController *navigation = [[RoutePlanViewController alloc] init];
            navigation.destinationPoint = [[CLLocation alloc] initWithLatitude:[self.traceModel.gdLat doubleValue] longitude:[self.traceModel.gdLng doubleValue]];
            [self.navigationController
             pushViewController:navigation animated:YES];
        }
            break;
        default:
            break;
    }
}

- (void)pushToNextPageWithClass:(Class)class
{
    [self.navigationController pushViewController:[self getViewControllerFromClass:class] animated:YES];
}

- (UIViewController *)getViewControllerFromClass:(Class)class {
    return [[class alloc]init];
}

/* 加载最新的设备信息 */
- (void)loadEquipLatestInfo:(NSString *)eqNo
{
    [self.requestTool loadRealTrackByEqno:eqNo show:YES success:^(TraceModel *traceModel) {
        self.traceModel = traceModel;
//        PPLog(@"555 = %@",self.traceModel.postType);
        ///<1>.逆地理编码
        [self searchReGeocodeWithCoordinate:CLLocationCoordinate2DMake([traceModel.gdLat doubleValue], [traceModel.gdLng doubleValue])];
        
        ///<2>.刷新标注点的位置
        [self.annotation setCoordinate:CLLocationCoordinate2DMake([traceModel.gdLat doubleValue], [traceModel.gdLng doubleValue])];
        
        ///<3>.刷新地图中心点
        [self.mapView setCenterCoordinate:self.annotation.coordinate];
        
    } failure:^(NSError *error) {
        PPLog(@"load real track error = %@",error);
    }];
}

- (void)searchReGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    [ReGeocodeManager searchReGeocodeWithCoordinate:coordinate reGeocodeBlock:^(AMapReGeocode *reGeocode) {
        AMapPOI *poi = reGeocode.pois[0];
        NSString *format = reGeocode.formattedAddress;
        NSString *poiname = poi.name;
        
        if ([format containsString:poiname]) poiname = @"";
        
        self.traceModel.address = NSStringFormat(@"%@%@ %@ %ldm",format,poiname,[Utility turnDirection:poi.direction],poi.distance);
        [self.annotationView setTraceModel:self.traceModel];
    } reGeocodeFailBlock:^(NSString *errcode) {
        self.traceModel.address = errcode;
        [self.annotationView setTraceModel:self.traceModel];
    }];
}

- (void)setupNavgationBar
{
    self.searchView = [[SearchView alloc] init];
    self.searchView.sd_layout.heightIs(45).widthIs(kScreenWidth*0.95);
    self.navigationItem.titleView = self.searchView;
    self.searchView.textField.delegate = self;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.searchView.textField resignFirstResponder];
    
    SearchViewController *search = [[SearchViewController alloc] init];
    search.delegate = self;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:search];
//    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - SearchTableViewCellDelegate -

- (void)annotationFromSearchTableViewCell:(CLLocationCoordinate2D)selectedCoord
{
    [self.mapView setCenterCoordinate:selectedCoord animated:YES];
    [self.mapView setZoomLevel:19 animated:YES];
}

#pragma mark - Action Handlers -

- (void)userLocation:(UIButton *)sender
{
    if (![LocationManager isLocationEnabled]) {// 用户拒绝开启定位权限
        [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启)，定位您当前位置" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil] show];
        return;
    }
    
    MAMapStatus *status = [self.mapView getMapStatus];
    
    status.screenAnchor = CGPointMake(0.5,0.5);
    
    [self.mapView setMapStatus:status animated:YES];
    
    [self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:YES];
    
    if (self.mapView.userTrackingMode == MAUserTrackingModeNone)
    {
        [self.mapView setUserTrackingMode:MAUserTrackingModeFollow];
    }
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

- (void)magnify:(UIButton *)sender
{
    CGFloat oldZoom = self.mapView.zoomLevel;
    [self.mapView setZoomLevel:(oldZoom + 1) animated:NO];
}

- (void)shrink:(UIButton *)sender
{
    CGFloat oldZoom = self.mapView.zoomLevel;
    [self.mapView setZoomLevel:(oldZoom - 1) animated:NO];
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kSendBtnTitleNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    // 导航栏不透明
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}


@end
